<script setup lang="ts">
import { User, Lock } from '@element-plus/icons-vue'
import { ElNotification } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import useUserStore from '@/store/modules/user.ts'
import { reqLogin } from '@/api/user'
import { getTime } from '@/utils/time.ts'

import type { FormRules, FormInstance } from 'element-plus'
import type { LoginResponseData } from '@/api/user/type.ts'

const $router = useRouter()
const $route = useRoute()

const userStore = useUserStore()

interface LoginForm {
  username: string
  password: string
}
const loginFormRef = ref<FormInstance>()
const loginForm = reactive<LoginForm>({
  username: 'admin',
  // password: 'atguigu123',
  password: '111111',
})

const validatePassword = (rule: any, value: any, callback: any) => {
  console.log('rule :>> ', rule)
  if (value.length >= 6) {
    callback() // 通过
  } else {
    callback(new Error('密码长度至少6位'))
  }
}

const rules = reactive<FormRules<LoginForm>>({
  username: [
    { required: true, message: '用户名不能为空', trigger: 'blur' },
    { max: 10, message: '账号长度最多10位', trigger: 'change' },
  ],
  // password: [
  //   { required: true, message: '密码不能为空', trigger: 'blur' },
  //   { min: 6, message: '密码长度至少6位', trigger: 'change' },
  // ],
  password: [{ validator: validatePassword, trigger: 'change' }],
})

const loginValue = ref(false)
const login = async () => {
  loginValue.value = true
  try {
    // 校验参数
    await loginFormRef.value?.validate()

    // 登录接口
    const { code, data, message }: LoginResponseData = await reqLogin(loginForm)

    if (code === 200) {
      userStore.updateToken(data as string)
      let redirectUrl: any = $route.query.redirect ? $route.query.redirect : '/'
      // 重定向
      await $router.push({
        path: redirectUrl,
      })
      ElNotification({
        type: 'success',
        message: '欢迎回来',
        title: `${getTime()}好！`,
      })
    } else {
      ElNotification({
        type: 'error',
        message: data ?? message,
      })
    }
  } catch (e: any) {
    e.message &&
      ElNotification({
        type: 'error',
        message: (e as Error).message,
      })
  } finally {
    loginValue.value = false
  }
}
</script>

<template>
  <div class="login_container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form
          class="login_form"
          :model="loginForm"
          :rules="rules"
          ref="loginFormRef"
        >
          <h1>Hello</h1>
          <h2>欢迎来到硅谷甄选</h2>
          <el-form-item prop="username">
            <el-input v-model="loginForm.username" :prefix-icon="User" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              type="password"
              v-model="loginForm.password"
              :prefix-icon="Lock"
              show-password
            />
          </el-form-item>
          <el-form-item>
            <el-button
              :loading="loginValue"
              class="login_btn"
              type="primary"
              size="default"
              @click="login"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped lang="scss">
.login_container {
  width: 100vw;
  height: 100vh;
  background: url('@/assets/images/background.jpg') no-repeat;
  background-size: cover;

  .login_form {
    position: relative;
    top: 30vh;
    width: 60%;
    min-width: 320px;
    padding: 40px;
    margin: 0 auto;
    background: url('@/assets/images/login_form.png') no-repeat;
    background-size: 100% 100%;

    h1 {
      font-size: 40px;
      color: #fff;
    }

    h2 {
      margin: 20px 0;
      font-size: 20px;
      color: #fff;
    }

    .login_btn {
      width: 100%;
    }
  }
}
</style>
